<?php

class MemberController extends Controller {

    public $layout = '//layouts/column2';

    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
        );
    }

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('signup', 'signupView', 'captcha'),
                //'actions' => array('index', 'view', 'signup', 'signupView', 'captcha'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
//              'actions' => array('create', 'update'),
                'actions' => array('update', 'updatepp', 'membergraph','balancestatus'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete', 'index', 'view', 'create'),
                //'users' => array('admin'),
                'expression' => '$user->isAdmin()'
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionSignupView($id, $isSignup) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
            'isSignup' => $isSignup,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionSignup($refkey, $type) {
        require_once "protected/utility/Util.php";
        $modelForm = new MemberForm;
        $_SESSION['NEWSIGNUP_MEMBER'] = NULL;

        if (isset($_POST['MemberForm'])) {
            $this->performAjaxValidation($modelForm);
            $modelForm->attributes = $_POST['MemberForm'];
            
            $member = new Member;
            $member->attributes = $_POST['MemberForm'];
            
            $member->plain_password = $modelForm->password;
            $member->password = sha1(md5($modelForm->password));
            
            $member->create_date = date("Y-m-d H:i:s");
            $member->active = 0;
            $member->status = 0; 
            $member->tmp = 1;
            $member->upline_key = uniqid();
            $member->confirmation_code = Util::getUniqueId();
            $member->tmp_package_id = $modelForm->package_id;
            $member->package_id = NULL;
            
            
            $adminUser = Member::model()->findByAttributes(array('username' => 'admin'));
            $member->upline_id = $adminUser->member_id;
            if (isset($_POST['MemberForm']['upline'])) {
                $upmodel = Member::model()->findByAttributes(array('upline_key' => $_POST["MemberForm"]["upline"]));
                if ($upmodel != null) {
                    $member->upline_id = $upmodel->member_id;
                }
            }
            
            $member->member_type = 'A';
            if (isset($_POST['MemberForm']['type'])) {
                if($_POST['MemberForm']['type'] == 'A'){
                    $member->member_type = 'A';
                }else if($_POST['MemberForm']['type'] == 'B'){
                    $member->member_type = 'B';
                }
            } 
            if ($member->save()) {
                if ($modelForm->paymentmethod_id != null) {
                    $modelDeposit = new DipositForm();

                    // add transaction
                    $package = Package::model()->findByAttributes(array('package_id' => $modelForm->package_id));
                    $modelDeposit->amount = $package->price;
                    $modelDeposit->method = $modelForm->paymentmethod_id;
                    $modelDeposit->package = $modelForm->package_id;
                    
                    // save member model into session
                    $_SESSION['NEWSIGNUP_MEMBER'] = $member;
                    
                    $this->render('payment_gateway', array(
                        'model' => $modelDeposit,
                    ));
                }

//                $this->redirect(array('signupView', 'id' => $model->member_id, 'isSignup' => 'Y'));
            }
        }

        if (isset($refkey)) {
            $modelForm->upline = $refkey;
        }
        
        if (isset($type)) {
            $modelForm->member_type = $type;
        }

        $this->render('_form_signup', array(
            'model' => $modelForm,
        ));
    }

    public function actionCreate() {
        require_once "protected/utility/Util.php";
        $model = new Member;

        $this->performAjaxValidation($model);

        if (isset($_POST['Member'])) {
            $model->attributes = $_POST['Member'];
            // saving user information
            $psd = $model->password;
            $model->plain_password = $model->password;
            $model->password = sha1(md5($model->password));
            $model->upline_key = uniqid();
            $model->confirmation_code = Util::getUniqueId();
            $model->upline_id = $model->parent_id;
            $model->save();

            //$hierarchy = $model->member_id;

            if ($model->parent_id == null) {
                $adminUser = Member::model()->findByAttributes(array('username' => 'admin'));
                $model->parent_id = $adminUser->member_id;
            }
            if ($model->parent_id != null) {
                $parentUser = Member::model()->findByAttributes(array('member_id' => $model->parent_id));
                if($parentUser == NULL){
                    $parentUser = $adminUser;
                }
                
                $model->upline_id = $model->parent_id;
                // place on tree
                if ($model->member_type == 'A') {
                    $aModel = $this->traverseASide($parentUser);
                    $aModel->a_child_id = $model->member_id;
                    $aModel->update();
                } else if ($model->member_type == 'B') {
                    $bModel = $this->traverseBSide($parentUser);
                    $bModel->b_child_id = $model->member_id;
                    $bModel->update();
                }
            }

            //$model->hierarchy = $hierarchy;



            if ($model->update()) {
                $this->referralTransaction($model);
                $this->pointCalculation($model);
                $this->sendConfirmationRequestEmail($model);
                $this->sendSuccessfulTransactionEmail($model);
                $this->redirect(array('view', 'id' => $model->member_id));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function pointCalculation($member) {
        $package = Package::model()->findByAttributes(array('package_id' => $member->package_id));

        $parent = Member::model()->find("a_child_id=:a_child_id or b_child_id=:b_child_id", array('a_child_id' => $member->member_id, 'b_child_id' => $member->member_id));
        $child = $member;
        while ($parent != null) {
            //echo $parent->member_id;
            if ($member->member_type == 'A' && $parent->a_child_id == $child->member_id) {
                $parent->a_point = $parent->a_point + $package->point;
                $parent->update();
            } else if ($member->member_type == 'B' && $parent->b_child_id == $child->member_id) {
                $parent->b_point = $parent->b_point + $package->point;
                $parent->update();
            }
            $child = $parent;
            $parent = Member::model()->find("a_child_id=:a_child_id or b_child_id=:b_child_id", array('a_child_id' => $parent->member_id, 'b_child_id' => $parent->member_id));
        }
    }

//    public function referralTransaction($member, $payment_processors_id, $payment_processors_name) {
    public function referralTransaction($member) {
        $package = Package::model()->findByAttributes(array('package_id' => $member->package_id));

        // current member transaction
        $mt = new MemberTransactionHistory();
        $mt->member_id = $member->member_id;
        $mt->debit = $package->price;
        $mt->credit = 0;
        $mt->transaction_date = date("Y-m-d H:i:s");
        $mt->particulars = "Deposit from Perfect Money"; // need dynamic
        $mt->isDeposit = "1";
        $mt->save();

        // referral income
        if ($member->upline_id != NULL) {
            $firstUpMember = Member::model()->findByAttributes(array('member_id' => $member->upline_id));
            $mt = new MemberTransactionHistory();
            $mt->member_id = $firstUpMember->member_id;

            $referrel_firstup_percentage = Yii::app()->params['referral_firstup'];
            $credit = ($package->price * $referrel_firstup_percentage) / 100;
            $cBalance = $this->getCurrentUserBalance($firstUpMember->member_id);

            $mt->particulars = $referrel_firstup_percentage . "% referral amount by referring " . $member->username;
            $mt->debit = 0;
            $mt->credit = $credit;
            $mt->balance = $cBalance + $credit;
            $mt->ref_id = $member->member_id;
            $mt->transaction_date = date("Y-m-d H:i:s");
            //$mt->payment_processors_id = $payment_processors_id;
            $mt->isReferralEarning = "1";
            $mt->save();
        }
    }

    function traverseASide($rootNode) {
        $prevRootNode = null;
        while ($rootNode->a_child_id != null) {
            $prevRootNode = $rootNode;
            $rootNode = Member::model()->findByAttributes(array('member_id' => $rootNode->a_child_id));
            if($rootNode == NULL || $rootNode->member_id == NULL){
                $rootNode = $prevRootNode;
                $rootNode->a_child_id = NULL;
                $rootNode->save();
            }
        }
        return $rootNode;
    }

    function traverseBSide($rootNode) {
        $prevRootNode = null;
        while ($rootNode->b_child_id != null) {
            $prevRootNode = $rootNode;
            $rootNode = Member::model()->findByAttributes(array('member_id' => $rootNode->b_child_id));
            if($rootNode == NULL || $rootNode->member_id == NULL){
                $rootNode = $prevRootNode;
                $rootNode->b_child_id = NULL;
                $rootNode->save();
                
            }
        }
        return $rootNode;
    }

    public function actionMembergraph() {
        $model = new Member;
        $this->render('membergraph', array(
            'model' => $model,
        ));
    }
    
    public function actionBalancestatus() {
        $model = new Member;
        $this->render('balancestatus', array(
            'model' => $model,
        ));
    }

    public function actionUpdate($id) {
        $sqList = SecurityQuestion::model()->findAll();
        $sqArr = CHtml::listData($sqList, 'secutiry_question_id', 'question');

        $model = $this->loadModel($id);
        $oldPass = $model->password;

        $oldMemberType = $model->member_type;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Member']) && $model->username != 'admin') {
            $model->attributes = $_POST['Member'];
            if ($oldPass != $model->password) {
                $model->plain_password = $model->password;
                $model->password = sha1(md5($model->password));
            }

            $model->upline_id = $model->parent_id;
            if ($oldMemberType != 'A' && $oldMemberType != 'B') {
                if ($model->parent_id == null) {
                    $parentUser = Member::model()->findByAttributes(array('username' => 'admin'));
                    $model->parent_id = $parentUser->member_id;
                } else {
                    $parentUser = Member::model()->findByAttributes(array('member_id' => $model->parent_id));
                }
                if ($model->member_type == 'A') {
                    $aModel = $this->traverseASide($parentUser);
                    $aModel->a_child_id = $model->member_id;
                    $aModel->update();
                } else if ($model->member_type == 'B') {
                    $bModel = $this->traverseBSide($parentUser);
                    $bModel->b_child_id = $model->member_id;
                    $bModel->update();
                }
                $this->referralTransaction($model);
                $this->pointCalculation($model);
            }

            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->member_id));
            }
        }

        $this->render('update', array(
            'model' => $model,
            'securityQues' => $sqArr,
        ));
    }

    public function actionUpdatepp() {

        $memberAccountEP = MemberAccount::model()->find("member_id=:member_id AND payment_processors_id=:payment_processors_id", array("member_id" => Yii::app()->user->id, "payment_processors_id" => PaymentProcessor::model()->findByAttributes(array('code' => 'EP'))->payment_processors_id));
        $memberAccountPM = MemberAccount::model()->find("member_id=:member_id AND payment_processors_id=:payment_processors_id", array("member_id" => Yii::app()->user->id, "payment_processors_id" => PaymentProcessor::model()->findByAttributes(array('code' => 'PM'))->payment_processors_id));

        $model = new MemberEditForm;

        if (isset($_POST['MemberEditForm'])) {
            $model->attributes = $_POST['MemberEditForm'];
            //var_dump($model);
            if ($memberAccountEP) {
                $memberAccountEP->account1 = $model->ego_pay;
                $memberAccountEP->save();
            } else {
                $memberAccountEP = new MemberAccount;
                $memberAccountEP->account1 = $model->ego_pay;
                $memberAccountEP->member_id = Yii::app()->user->id;
                $memberAccountEP->payment_processors_id = PaymentProcessor::model()->findByAttributes(array('code' => 'EP'))->payment_processors_id;
                $memberAccountEP->save();
            }
            if ($memberAccountPM) {
                $memberAccountPM->account1 = $model->perfect_money;
                $memberAccountPM->save();
            } else {
                $memberAccountPM = new MemberAccount;
                $memberAccountPM->account1 = $model->perfect_money;
                $memberAccountPM->member_id = Yii::app()->user->id;
                $memberAccountPM->payment_processors_id = PaymentProcessor::model()->findByAttributes(array('code' => 'PM'))->payment_processors_id;
                $memberAccountPM->save();
            }
            $this->redirect(array('dashboard/index'));
        } else {
            if ($memberAccountEP) {
                $model->ego_pay = $memberAccountEP->account1;
            }
            if ($memberAccountPM) {
                $model->perfect_money = $memberAccountPM->account1;
            }
        }

        $this->render('_member_edit_form', array('model' => $model));
    }

    public function actionDelete($id) {
        $model = $this->loadModel($id);
        //$model->active = 0;
        //$model->status = 0;
        //$model->a_child_id = "";
        //$model->b_child_id = "";
        //$model->update();

        $mt = MemberTransactionHistory::model()->findByAttributes(array('member_id' => $model->member_id));
        if ($mt->member_transaction_history_id != null) {
            $mt->delete();
        }
        $model->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Member');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Member('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Member']))
            $model->attributes = $_GET['Member'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function loadModel($id) {
        $model = Member::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'member-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
    
    public function sendConfirmationRequestEmail($member){
        try {
            $subject = "[viewInvesta] Please verify your account";
            $body = "DO NOT REPLY TO THIS EMAIL!\n***************************\n\n\n";
            $body = $body . "Dear " . $member->username . ",\n\n";
            $body = $body . "Thanks for choosing us. Your account have been created. We are waiting for your confirmation.\n\n";
            $body = $body . "Please, follow the link to activate your account: " . Yii::app()->request->getBaseUrl(true) . Yii::app()->params->email['confrimation_url'] . '?code=' . $member->confirmation_code . "\n\n";
            $body = $body . "Best Regards,\n";
            $body = $body . "The ViewInvesta Team\n";

            // send confirmation email to requested user email
            $from = 'From: ' . Yii::app()->params['senderEmail'];
            mail($member->email, $subject, $body, $from);
        } catch (Exception $e) {
            
        }
    }
    
    public function sendSuccessfulTransactionEmail($member){
        try {
            $package = Package::model()->findByAttributes(array('package_id' => $member->package_id));
            
            $subject = "[viewInvesta] Package Buy Notification";
            $body = "Dear " . $member->username . ",\n\n";
            $body = $body . "You have bought a " . $package->name . " ($" . $package->price . ") package successfully .\n\n";
            $body = $body . "Best Regards,\n";
            $body = $body . "The Viewinvesta Team\n";

            // send confirmation email to requested user email
            $from = 'From: ' . Yii::app()->params['paymentEmail'];
            mail($member->email, $subject, $body, $from);
        } catch (Exception $e) {
            
        }
    }

}